package com.base.common.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.base.common.util.Utils;
import com.google.gson.Gson;
import com.lovenote.common.global.GlobalDefine;

/**
 * 权限过滤器
 * 
 * @author xingkong1221
 *
 */
public class SecurityFilter implements Filter {
	private static final Logger logger = Logger.getLogger(SecurityFilter.class);
	

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		// Get the current session associated with this request 
		HttpSession session = request.getSession();
		
		String status = (String) session.getAttribute("status");
		if (!StringUtils.isEmpty(status) && GlobalDefine.USER_STATUS.IN.equals(status)) {
			// User is online, continue the request
			chain.doFilter(request, response);
		} else {
			// User if offline
			
			// Detect if a ajax request
			String isAjax = request.getParameter("isAjax");
			if (!StringUtils.isEmpty(isAjax) && Integer.parseInt(isAjax) == 1) {
				// Ajax request
				response.setContentType("application/json;charset=UTF-8");
				Map<String, Object> result = new HashMap<String, Object>();
				result.put("noAuth", true);
				StringBuilder url = new StringBuilder(request.getContextPath());
				result.put("url", url.append("/login").toString());
				// Convert map to json
				Gson gson = new Gson();
				String json = gson.toJson(result);
				//Output json to client
				PrintWriter out = response.getWriter();
				out.print(json);
				out.flush();
			} else {					
				// Not ajax request
				logger.info("Unauthorized access, ip = " + Utils.getRealAddr(request));
				response.sendRedirect(request.getContextPath() + "/login");
			}
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
